import { Device } from "@/api/interface/iot";
import { getHistoryDataList } from "@/api/modules/iot/data";
import titleIcon from "@/assets/images/dashboard/icon-18.png";
import BaseChart from "@/components/Chart/BaseChart.vue";
import { formatSize } from "@/utils/format";
import * as echarts from "echarts";
import { YAXisOption } from "echarts/types/dist/shared";
import { dayjs } from "element-plus";
import ItemBlock from "../components/item-block";
import { ComponentInternalInstance, defineComponent, getCurrentInstance, ref } from "vue";
import "./center.scss";
export default defineComponent({
	emits: [],
	setup(props, { expose }) {
		const { proxy } = getCurrentInstance() as ComponentInternalInstance;
		let optionTemplate: any = {
			tooltip: {
				trigger: "axis",
				formatter: "{b} <br/> {a}: {c} %",
				axisPointer: {
					type: "shadow"
				}
			},
			toolbox: { show: false },
			legend: { show: false },
			grid: {
				top: "30px",
				left: "3%",
				right: "2%",
				bottom: "3%",
				containLabel: true
			},
			xAxis: [
				{
					axisLabel: {
						rotate: 0,
						color: "#555"
					},
					boundaryGap: false,
					type: "category",
					data: []
				}
			],
			yAxis: [
				{
					splitLine: { show: true, lineStyle: { color: "#e8e8e8" } },
					type: "value",
					axisLabel: {
						formatter: `{value}%`,
						fontWeight: 500,
						color: "#555"
					}
				}
			] as YAXisOption[],
			series: [] as any[]
		};
		// const state = reactive({
		// 	typeList: [
		// 		{
		// 			key: "cpu",
		// 			label: "CPU"
		// 		},
		// 		{
		// 			key: "mem",
		// 			label: proxy?.$t("index.type_list_label.mem")
		// 		},
		// 		{
		// 			key: "disk",
		// 			label: proxy?.$t("index.type_list_label.disk")
		// 		},
		// 		{
		// 			key: "net",
		// 			label: proxy?.$t("index.type_list_label.net")
		// 		}
		// 	],
		// 	sensorKey: "cpu"
		// });
		const state = ref({
			typeList: [
				{
					key: "cpu",
					label: "CPU"
				},
				{
					key: "mem",
					label: proxy?.$t("index.type_list_label.mem")
				},
				{
					key: "disk",
					label: proxy?.$t("index.type_list_label.disk")
				},
				{
					key: "net",
					label: proxy?.$t("index.type_list_label.net")
				}
			],
			sensorKey: "cpu"
		});
		const chart = ref();
		const resize = () => {
			chart.value.resize();
		};
		const load = async (type?: string) => {
			if (!type) {
				type = state.value.sensorKey;
			}
			if (type != state.value.sensorKey) {
				state.value.sensorKey = type;
			}
			getHistoryDataList({
				idSn: "ssiot-sysinfo-master",
				key: state.value.sensorKey,
				keyType: "sensor",
				pageIndex: 1,
				pageSize: 100,
				timeOrder: "desc"
			}).then((res: any) => {
				let dataList = (res.result?.records || []) as Device.ResDataInfo[];
				dataList = dataList?.reverse();
				//根据最大值获取单位
				let max = 0;
				let maxParam: { size: number; unit: string; scale: number } = { size: 0, unit: "b", scale: 1 };
				let option = JSON.parse(JSON.stringify(optionTemplate));
				option.xAxis[0].data = [];
				option.yAxis[0].axisLabel.formatter = `{value}%`;
				option.tooltip.formatter = "{b} <br/> {a}: {c} %";
				if (state.value.sensorKey == "net") {
					//添加多个y轴
					dataList.forEach(item => {
						let val = Number(item.value?.rx || 0 + item.value?.tx || 0);
						max = max >= val ? max : val;
					});
					maxParam = formatSize(max);
					option.series = [barSeries(`上行流量`), barSeries(`下行流量`)];
					option.yAxis = [getYAxis(maxParam.unit)];
					option.tooltip.formatter = `{b} <br/> {a}: {c} ${maxParam.unit} <br/> {a1}: {c1}${maxParam.unit} `;
				} else if (state.value.sensorKey == "mem") {
					//添加多个y轴
					option.series = [lineSeries("內存使用")];
					dataList.forEach(item => {
						max = max >= item.value?.memoryTotal ? max : item.value?.memoryTotal;
					});
					maxParam = formatSize(max);
					option.yAxis = [getYAxis("%")];
				} else if (state.value.sensorKey == "cpu") {
					option.series = [lineSeries("CPU使用")];
				} else if (state.value.sensorKey == "disk") {
					//添加多个y轴
					option.series = [lineSeries("磁盘使用")];
					dataList.forEach(item => {
						max = max >= item.value?.diskTotal ? max : item.value?.diskTotal;
					});
					maxParam = formatSize(max);
					option.yAxis = [getYAxis("%")];
				}
				dataList.map((item: any) => {
					let dts = dayjs(item.updateTime);
					let time = dts.isValid() ? dts.format("MM-DD HH:mm") : item.updateTime;
					option.xAxis[0].data.push(time);
					option.xAxis[0].axisLabel.formatter = (value: any) => {
						return dayjs(value).format("HH:mm");
					};
					switch (state.value.sensorKey) {
						case "cpu":
							option.series[0].data.push(item.value?.used ? item.value?.used.toFixed(1) : null);
							break;
						case "disk":
							option.series[0].data.push(item.value?.diskUsed ? item.value?.diskUsed.toFixed(1) : null);
							break;
						case "mem":
							//添加每个轴数据项
							option.series[0].data.push(item.value?.memUsed ? item.value?.memUsed.toFixed(1) : null);
							break;
						case "net":
							//添加每个轴数据项
							option.series[0].itemStyle.color = "#38cb80";
							option.series[0].emphasis = null;
							option.series[0].data.push(item.value?.rx ? (item.value?.rx / maxParam.scale).toFixed(1) : null);

							option.series[1].itemStyle.color = "#1f97ff";
							option.series[1].emphasis = null;
							option.series[1].data.push(item.value?.tx ? (item.value?.tx / maxParam.scale).toFixed(1) : null);
							break;
					}
				});
				chart.value.setChart(option);
			});
		};
		const barSeries = (name: string) => {
			return {
				name: name,
				type: "bar",
				stack: "stack",
				itemStyle: {
					color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
						{ offset: 0, color: "#38cb80" },
						{ offset: 1, color: "#1f97ff" }
					])
				},
				emphasis: {
					//鼠标移动上去高亮
					focus: "series",
					blurScope: "coordinateSystem",
					itemStyle: {
						color: "#38cb80"
					}
				},
				data: []
			};
		};
		const lineSeries = (name: string) => {
			return {
				type: "line",
				smooth: true,
				stack: "stack",
				name: name,
				// 折线图线条颜色
				lineStyle: {
					color: "#1fc4e3",
					width: 2
				},
				showSymbol: false,
				markPoint: { data: undefined },
				//区域图-背景
				areaStyle: {
					opacity: 1,
					color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
						{
							offset: 0, //底部
							color: "#a8e7fe99"
						},
						{
							offset: 1, //顶部
							color: "#a8e7fe10"
						}
					])
				},
				data: []
			};
		};
		const getYAxis = (unit: string): YAXisOption => {
			return {
				splitLine: { show: true, lineStyle: { color: "#e8e8e8" } },
				type: "value",
				axisLabel: {
					formatter: `{value} ${unit}`,
					fontSize: 13,
					fontWeight: 500,
					color: "#555"
				}
			};
		};
		expose({ resize, load });
		return () => {
			return (
				<ItemBlock class="system-chart" title={proxy?.$t("index.chart_title.system")} unit={proxy?.$t("index.chart_unit.pieces")}>
					{{
						titleIcon: () => {
							return <el-image src={titleIcon} fil="cover" />;
						},
						subjectInfo: () => {
							return (
								<div class="flex">
									{state.value.typeList.map(item => {
										return (
											<div
												class={["btn", state.value.sensorKey == item.key ? "active" : ""]}
												onClick={() => {
													chart.value.initChart();
													load(item.key);
												}}
											>
												{item.label}
											</div>
										);
									})}
								</div>
							);
						},
						default: () => {
							return <BaseChart ref={chart} dateType="line" width="100%" height="100%" />;
						}
					}}
				</ItemBlock>
			);
		};
	}
});
